package com.cib.leetcode.easy.link;

/**
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 *
 * @author goomba
 **/
public class Function21 {

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode header = new ListNode(0);
        ListNode current = new ListNode(0);
        header.next = current;

        while (list1 != null || list2 != null) {
            boolean isLeftLarger = isLeftLarger(list1, list2);
            if (isLeftLarger) {
                current.next = list1;
                list1 = list1.next;
                current = current.next;
            } else {
                current.next = list2;
                list2 = list2.next;
                current = current.next;
            }
        }
        return header.next.next;
    }


    private boolean isLeftLarger(ListNode left, ListNode right) {
        if (left == null) return false;
        if (right == null) return true;
        return left.val < right.val;
    }


    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
